<template>
    <view class="content">
        <van-popup
            position="bottom"
            @click-overlay="closePopup"
            :show="showSpecsPopup"
            round
            custom-style="width: 100%;background:#ffffff;overflow: hidden; height:70%">
            <view class="popup-content">

                <view class="popup-main">
                    <view style="display: flex; justify-content: space-between;">
                        <!-- 商品内容 -->
                        <view class="goodsDetail">
                            <view class="goodsPic"> <img
                                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/judge01.png"
                                alt=""
                                mode="widthFix"> </view>
                            <view class="goodsText">
                                <view class="goods_price">
                                    <view class="goods_price_num r13">¥{{price}}</view>
                                    <view class="goods_price_text r8">最多可用</view>
                                    <view class="goods_price_num"> <img
                                        src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                        alt=""
                                        style="height: 14px; width: 14px; margin-right: 7px;" /> {{score}}</view>
                                </view>
                                <view class="goods_T" v-if="biaozhi!=='find'">{{ebStoreProduct.storeName}} {{selectSpecs}}</view>
                                <view class="goods_T" v-if="biaozhi==='find'">{{ ebStoreProduct.title }} {{selectSpecs}}</view>
                            </view>
                        </view>
                        <!-- 关闭弹窗按钮 -->
                        <view>
                            <van-icon name="cross" color="#FFFFFF" size="15" @click="closePopup" />
                        </view>
                    </view>
                    <scroll-view class="scroll-content " scroll-y :lower-threshold="120" show-scrollbar="false">

                        <!-- 规格   口味 -->

                        <view class="specs-box taste" v-for="(item,index) in specsList" :key="index" :id="item.id">
                            <view class="specs-box-title">{{item.attrName}}</view>
                            <view class="specs-box-select">
                                <view class="popup-sort">
                                    <!-- :class="{'inStock':item.stock>0, 'soldOut' :item.stock<=0 ,  active:curSpecsOuterIndex === index  }" -->
                                    <view
                                        class="popup-item inStock"
                                        :class="{ active: curObj[index].id===ele.id ||(curObj.length===1 &&  curObj[0].id===ele.id) ||(item.curObj.id===ele.id) }"
                                        v-for="(ele, val) in item.ebProductAttrSecond"
                                        :key="val"
                                        :id="ele.id"
                                        @click="onClickSpecs(index,item, val,ele)">{{ ele.attrName }}</view>
                                </view>
                            </view>

                        </view>
                        <!-- 重量 -->
                        <!-- <view class="specs-box weight">
                            <view class="specs-box-title">重量</view>
                            <view class="specs-box-select">
                                <view class="popup-sort">
                                    <view
                                        class="popup-item inStock"
                                        :class="{ active: curWeight === index }"
                                        v-for="(item, index) in weightData"
                                        :key="index"
                                        @click="onClickWeight(index, $event, item.weight)">{{ item.weight }}</view>
                                </view>
                            </view>
                        </view> -->

                        <!-- 数量 -->
                        <view class="specs-box number">
                            <view class="specs-box-title">数量 <span v-if="ebStoreProduct.quotaNum && ebStoreProduct.quotaNum>0">（限购{{ebStoreProduct.quotaNum}}{{ebStoreProduct.unitName}}）</span> </view>
                            <view class="specs-box-select">
                                <van-stepper :value="stepperValue" min="1" :max="ebStoreProduct.quotaNum" integer />
                            </view>
                        </view>

                        <van-toast id="van-toast" />
                    </scroll-view>

                </view>
                <view class="goodsAction nav_box" v-if="parentSign==='detail'">
                    <van-goods-action class="my-goods-action" v-if="buttonStatus === 0">
                        <van-goods-action-button
                            class="my-action-buttonL"
                            plain
                            color="#111111"
                            text="加入购物车"
                            @click="addToCart" />
                        <van-goods-action-button color="#FF6203" text="立即购买" @click="onClickBuy" />
                    </van-goods-action>
                    <van-goods-action v-else>
                        <van-goods-action-button v-if="buttonStatus === 1" color="#FF6203" text="加入购物车" @click="addToCart" />
                        <van-goods-action-button v-if="buttonStatus===2 && biaozhi!=='find'" color="#FF6203" text="立即购买" @click="onClickBuy" />
                        <van-goods-action-button v-if="buttonStatus===2 && biaozhi==='find'" color="#FF6203" text="立即拼团" @click="onClickGroupBuy" />
                    </van-goods-action>
                </view>
                <view class="goodsAction nav_box" v-if="parentSign==='cart'">
                    <van-goods-action class="my-goods-action">
                        <van-goods-action-button color="#FF6203" text="确定" @click="onClickBuy" />
                    </van-goods-action>
                </view>
            </view>
        </van-popup>
    </view>
</template>
<script>
import Toast from '@/wxcomponents/vant/toast/toast'

import {addToShoppingCartApi} from '@/api/shoppingCart'

export default {
    props: {
        showSpecsPopup: {
            type: Boolean,
            default: () => false
        },
        roleName: {
            type: String,
            default: () => ''
        },
        buttonStatus: {
            type: Number,
            default: () => 0
        },
        parentSign: {
            type: String,
            default: () => ''
        },
        biaozhi: {
            type: String,
            default: () => ''
        },
        specsList:{
            type:Array,
            default:()=>[]
        },
        ebStoreProduct:{
            type: Object,
            default: () => {}
        },
        specsPriceList:{
            type:Array,
            default:()=>[]
        },
        specsAttrRelationDTO:{
            type:Array,
            default:()=>[]
        },
        productId:{
            type: String,
            default: () => ''
        }

    },
    data () {
        return {
            curSpecsOuterIndex: -1,
            curSpecsInnerIndex:-1,
            curWeight: -1,

            date: '',
            show: true,
            title: 'Hello',
            option: {},
            url: '',
            stepperValue: 1,
            weightData: [
                {
                    weight: '5斤装 主推款'
                },
                {
                    weight: '3斤装工厂回馈价'
                },
                {
                    weight: '2斤装'
                },
                {
                    weight: '1斤装'
                }
            ],
            selectSpecs:'',
            price:'160',
            score:'160',
            curObj:[],
            specsArray:[],
            newSpecsList:[],
            productId:undefined,
            productAttrValueId:undefined

        }
    },
    watch: {
        ebStoreProduct: {
            immediate: true, // 这句重要
            handler (newval, oldval) {
                console.log('newval' + newval, 'oldval' + oldval, '子组件watch')
                if (this.ebStoreProduct && this.ebStoreProduct.hasOwnProperty('id')) {
                    this.productId=this.ebStoreProduct.id
                }
                if (this.ebStoreProduct && this.ebStoreProduct.hasOwnProperty('price')) {
                    this.price = this.ebStoreProduct.price;
                }
                if (this.ebStoreProduct && this.ebStoreProduct.hasOwnProperty('integral')) {
                    this.score = this.ebStoreProduct.integral;
                }
            },
            deep: true
        },
        // specsList:{
        //     immediate: true, // 这句重要
        //     handler (val) {
        //         console.log('newval'+ val,val.length)
        //     },
        //     deep: true
        // },
        curObj:{
            immediate: true, // 这句重要
            handler (val) {
                console.log(val.length,'curObj',this.curObj)
                if (val.length > 1 && (val.length === this.specsList.length)) {

                    const filteredArray = this.specsAttrRelationDTO.filter((obj2) => {
                        return this.curObj.some((obj1) => obj1.id === obj2.specId);
                    });

                    console.log(filteredArray, 'filteredArray')

                    // array ：就是正在被操作的整个 filteredArray 数组本身。
                    this.specsArray = filteredArray.filter((current, index, array) => {   //创建一个新数组，新数组中的元素是满足给定条件的原数组元素。它会遍历 filteredArray 中的每个元素，并对每个元素执行传入的回调函数。
                        return filteredArray.some((other, otherIndex) => {   //other 另一个元素    some 方法用于检测数组中是否至少有一个元素满足指定的条件，只要有一个元素满足条件，它就返回 true，否则返回 false。在这里，它是作为外层 filter 方法回调函数中的条件判断逻辑使用。
                            return otherIndex !== index && other.valueId === current.valueId;
                        });
                    });
                    console.log(this.specsArray, 'specsArray')
                    this.specsPriceList.forEach((item, index) => {
                    const valueId = this.specsArray[0].valueId
                    this.productAttrValueId = this.specsArray[0].valueId
                    if (item.id === valueId) {
                        console.log(item, 'item')
                        this.price = item.price
                        this.score = item.integral
                        this.selectSpecs = item.suk
                    }
                })
                } else if (val.length === 1 && (val.length === this.specsList.length)) {
                    console.log(this.curObj,'yige ',this.curObj[0].id)
                    let valueId
                    this.specsAttrRelationDTO.forEach((item, index) => {
                        // console.log(item)
                        if (this.curObj[0].id === item.specId) {
                            valueId = item.valueId
                            this.productAttrValueId =  item.valueId
                        }
                    })
                    // debugger
                    this.specsPriceList.forEach(ele=>{
                        if (ele.id === valueId) {
                            this.price = ele.price
                            this.score = ele.integral
                            this.selectSpecs = ele.suk
                        }
                    })


                }
   
                   

            },
            deep: true

        },
        specsArray:{
            immediate: true, // 这句重要
            handler (val) {
                if(val.length>0){
                     // 从价格列表中过滤
                     this.specsPriceList.forEach((item,index)=>{
                        const valueId=this.specsArray[0].valueId
                        if(item.id===valueId){
                            console.log(item,'item')
                            this.price=item.price
                            this.score=item.integral
                            this.selectSpecs=item.suk
                        }
                    })
                }
            },
            deep: true
        },
        specsPriceList:{
            immediate: true, // 这句重要
            handler (val) {
                // this.specsPriceList.forEach((item,index)=>{
                //     const valueId=specsArray[0].valueId
                //     if(item.valueId===valueId){
                //         console.log(item,'item')
                //     }
                // })
            },
            deep: true
        },
        specsList:{
            immediate: true, // 这句重要
            handler (val) {
                if(val.length>0){
                    this.newSpecsList=this.specsList
                    console.log(this.newSpecsList,this.specsList,'iii')
                }
            },
            deep: true
        }
    },
    computed: {
        sortedArr() {
            return this.curObj.slice().sort((a, b) => a.specCategoryIndex - b.specCategoryIndex);
        }
    },
    onload(data){
        this.price=this.ebStoreProduct.price
        this.score=this.ebStoreProduct.integral
        this.productId=this.ebStoreProduct.id
    },
    onReady () {},
    methods: {
        // 选口味
        onClickSpecs (specCategoryIndex,specCategoryItem, specOptionIndex, specOption,) {
            console.log(specCategoryIndex,specCategoryItem.attrName, specOption.attrName,specOptionIndex,'规格')
            // 将当前点击规格分类对应的curObj属性赋值为当前点击的规格选项对象
            this.specsList[specCategoryIndex].curObj = specOption
            console.log(this.curObj,'被选的规格')
            
            specOption.specCategoryIndex=specCategoryIndex  // 给规格选项对象添加一个属性记录其所在的规格分类索引，
            console.log(specOption,'oooo')

            // 处理curObj数组插入逻辑
            if (this.curObj.length > 0) {
                if (specCategoryIndex < this.curObj.length) {
                    // 先查找curObj数组中是否已存在pid相同的元素
                    const existingIndex = this.curObj.findIndex(obj => obj.pid === specOption.pid);
                    if (existingIndex !== -1) {
                        // 如果存在，直接替换该位置的元素为specOption
                        // this.curObj[existingIndex] = specOption;
                        this.curObj.splice(existingIndex, 1, specOption);
                    } else {
                        // 如果不存在pid相同的元素，将specOption插入到specCategoryIndex位置
                        this.curObj.splice(specCategoryIndex, 0, specOption);
                        this.curObj=this.removeDuplicatesByPid(this.curObj)
                    }
                } else {
                    // 如果索引超出curObj已有长度，直接将元素i添加到数组末尾
                    // this.curObj.push(specOption);
                    this.curObj.splice(specCategoryIndex, 0, specOption);
                }
            } else {
                 // 如果curObj数组为空，添加元素i到数组
                this.curObj.push(specOption);
            }
           
        },

        removeDuplicatesByPid(arr) {
            const uniqueArr = [];
            const existingPids = new Set();
            arr.forEach((obj) => {
                if (!existingPids.has(obj.pid)) {
                    existingPids.add(obj.pid);
                    uniqueArr.push(obj);
                }
            });
            return uniqueArr;
        },

        // // 选重量
        // onClickWeight (val, e, item) {
        //     this.curWeight = val
        // },
        // 关闭弹窗
        closePopup () {
            this.$emit('closeSpecsPopup')
        },

        // 加入购物车
        addToCart() {
            // this.$emit('addToCart')
            if (this.curObj.length === 0) {
                Toast('请选择规格')
            } else {
                if (this.curObj.length === this.specsList.length) {
                    const params={
                        cartId:undefined,
                        cartNum: this.stepperValue,
                        cartType: "NORMAL",
                        // combinationId: 0,
                        productAttrValueId: this.productAttrValueId,
                        productId: this.productId,
                        selected: false
                    }
                    addToShoppingCartApi(params).then((res)=>{
                        if (res.code === 200) {
                            Toast('加入购物车成功')
                            this.$emit('closeSpecsPopup')
                        }
                    })
                    
                } else if (this.curObj.length < this.specsList.length) {
                    const idObject = {};
                    this.curObj.forEach((obj) => {
                        idObject[obj.pid] = true;
                    });
                    console.log(idObject,'idObject')
                    const missingItems = this.specsList.filter((obj) =>!idObject[obj.id]).map((obj) => obj.attrName);
                    console.log(missingItems,'missingItems')

                    Toast('请选择'+ missingItems)
                } else {

                }
            }
        },

        // 立即购买
        onClickBuy () {
              // this.$emit('onClickCart')
            if (this.curObj.length === 0) {
                Toast('请选择规格')
            } else {
                if (this.curObj.length === this.specsList.length) {
                    Toast('加入购物车成功')
                    // Toast('res.msg')
                    this.$emit('closeSpecsPopup')
                } else if (this.curObj.length < this.specsList.length) {
                    const idObject = {};
                    this.curObj.forEach((obj) => {
                        idObject[obj.pid] = true;
                    });
                    console.log(idObject,'idObject')
                    const missingItems = this.specsList.filter((obj) =>!idObject[obj.id])
                        .map((obj) => obj.attrName);
                    console.log(missingItems,'missingItems')

                    Toast('请选择'+ missingItems)
                } else {

                }
            }
        },
        onClickGroupBuy(){
            const params = {}
            uni.navigateTo({
                url:
                    '/pages/shoppingCart/settlement?params=' +
                    encodeURIComponent(JSON.stringify(params))
            })
        },
         // 加入购物车
         addToShoppingCartMethod(){
            
            return new Promise((resolve, reject) => {
                addToShoppingCartApi().then((res)=>{
                    console.log(res,'res')
                    if(res.code===200){

                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        }
    }
}
</script>
<style lang="scss" scoped>
// @import '@/styles/variables.scss';

// 最外层
.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    overflow-y: auto;
    z-index: -2;
    scrollbar-width: none;
    /* 针对Firefox */
}

// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}

// 提示框
.popup-content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 24px;
    border-radius: 16px;
    overflow: hidden;
    // height:100vh;
    height: 100%;

    .popup-main {
        display: flex;
        flex-direction: column;
        box-sizing: border-box;
        height: calc(100% - 30px);
    }

    .goodsDetail {
        display: flex;
        // align-items: center;
        padding-bottom: 8px;
        width: 100%;
    }

    .goodsPic {
        width: 25%;
        // 让图片居中
        display: flex;
        justify-content: center;
        align-items: center;

        img {
            width: 100%;
            height: auto;
            // width: 89px;
            // height: 89px;
        }
    }

    .goodsText {
        padding-left: 17px;
        position: relative;
        width: 75%;
        display: flex;
        flex-direction: column;
        justify-content: center;

        // 价格
        .goods_price {
            position: absolute;
            top: 5%;
            display: flex;
            align-items: center;
            // margin-top: 18px;
            text-align: left;
            // line-height: 20px;

            .goods_price_num {
                font-weight: bolder;
                font-size: 20px;
                text-align: left;
                color: #111111;
                line-height: 20px;
            }

            .goods_price_text {
                // font-weight: bold;
                font-size: 12px;
                text-align: left;
                color: #111111;
                line-height: 12px;
            }
        }

        .goods_T {
            position: absolute;
            // bottom: 10%;
            top: 45%;
            font-size: 12px;
            text-align: left;
            color: #888888;
            // line-height: 12px;
            // margin-top: 18px;
        }

    }

    // 选规格   口味 重量 数量
    .specs-box {
        margin-top: 28px;

        .specs-box-title {
            // font-weight: 400;
            font-size: 14px;
            text-align: left;
            color: #666666;
            line-height: 14px;

            span {
                // font-weight: 400;
                font-size: 14px;
                text-align: left;
                color: #111111;
                line-height: 14px;
            }
        }

        .specs-box-select {
            margin-top: 15px;
        }

        .popup-sort {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            flex-wrap: wrap;
        }

        .popup-item {
            margin-right: 12px;
            margin-bottom: 12px;
            height: 28px;
            line-height: 28px;
            padding-left: 24px;
            padding-right: 24px;
        }

        // 有库存
        .inStock {
            // width:33%;
            // flex: 0 0 calc((100% - 32px) / 3);
            border: 1px solid #D6D6D6;

            // font-weight: bold;
            font-size: 13px;
            text-align: center;
            color: #333333;

            &.active {
                border: 1px solid #111111;
                // font-weight: bolder;
                color: #111111;
                font-size: 14px;
            }
        }

        // 某一规格没有了
        .soldOut {
            font-size: 13px;
            color: #999999;
            border: 1px solid #999999;
        }

        //   .popup-item:nth-child(3n) {
        //         margin-right: 0;
        //     }
    }

    // 加入购物车按钮
    // .goodsAction {
    //     margin-top: 24px;
    //     width: calc(100% - 32px);
    // }

}

.number {
    padding-bottom: 20px;
}

.l20 {
    margin-left: 20px;
}

.r13 {
    margin-right: 13px;
}

.r8 {
    margin-right: 8px;
}

.my-goods-action {
    .van-goods-action-button {
        color: green;
        background-color: orange;
    }
}
// 商品导航 部分 左右边距  24px
::v-deep .van-goods-action, .van-goods-action--safe{
    border-top: 1px solid #f9f9f9 !important;
}

::v-deep .minus-class,
.van-stepper__minus,
.van-stepper__minus--disabled {
    border-radius: 50px !important;
}

// stepper    步进器
// 左边的数字
::v-deep .minus-class,
.van-stepper__minus {
    border-radius: 50px !important;
    background-color: #ffffff !important;
    border: 1px solid #111111 !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}

// 及不能被点击的最小数字
::v-deep .van-stepper__minus--disabled {
    border-radius: 50px !important;
    background-color: #ffffff !important;
    border: 1px solid #999999 !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}

// 中间的数字
::v-deep .input-class,
.van-stepper__input {
    border-radius: 50px !important;
    background-color: transparent !important;
}

// 右侧最大的数字
::v-deep .plus-class,
.van-stepper__plus {
    border-radius: 50px !important;
    background-color: #ffffff !important;
    border: 1px solid #111111 !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}

// 以及不能被点击状态
::v-deep .van-stepper__plus--disabled {
    border-radius: 50px !important;
    border: 1px solid #999999 !important;
    background-color: #ffffff !important;
    width: 23px !important;
    height: 23px !important;
    line-height: 23px !important;
}
</style>
